package com.itheima.gongjulei;

import java.util.Random;
import java.util.concurrent.Semaphore;

/*
信号量
Semaphore
 */
public class Demo02 {


    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3);
        Car car = new Car(semaphore);

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(car);
            thread.setName(i+"号车");
            thread.start();
        }
    }
}


class Car implements Runnable {
    private Semaphore semaphore;

    public Car(Semaphore semaphore) {
        this.semaphore = semaphore;

    }

    @Override
    public void run() {
        //新进入停车场  获取到了 信号量
        String name = Thread.currentThread().getName();
        try {
            System.out.println(name + "已经开始排队进入");
            semaphore.acquire();
            System.out.println(name + "进入停车场");

            // 开始停车
            int second = new Random().nextInt(200);
            System.out.println(name + "在停车场停了" + second + "秒");
            Thread.sleep(second);
            //停了指定的时间   开出去
            // 归还信号量
            semaphore.release();
            System.out.println(name+"开出去了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }




    }
}